package com.android.settings.audio.peq.soundeffect;

import android.text.TextUtils;

import com.google.gson.Gson;
import com.google.gson.annotations.SerializedName;
import com.google.gson.reflect.TypeToken;
import com.android.settings.R;
import com.android.settings.audio.peq.util.BuildConfig;
import com.android.settings.audio.peq.util.LogPlus;
import com.android.settings.audio.peq.util.ShareprefenceTool;
import com.android.settings.audio.peq.util.SmartPlayerApplication;

import org.json.JSONArray;
import org.json.JSONObject;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by We on 2023/4/12
 */
public class PeqDataManager {
    private PeqDataManager() {
    }

    private static class InstanceHolder {
        private static final PeqDataManager instance = new PeqDataManager();
    }

    public static PeqDataManager getInstance() {
        return InstanceHolder.instance;
    }

    public PeqDataItemInfo getCurrentSelectedPeqDataItem(List<PeqDataItemInfo> peqDataItemInfos) {
        if (peqDataItemInfos == null || peqDataItemInfos.isEmpty()) {
            return null;
        }
        //本地已有的所有列表数据
        PeqDataItemInfo currentSelectedPeqDataItem = null;
        for (PeqDataItemInfo peqDataItemInfo : peqDataItemInfos) {
            if (peqDataItemInfo.ischecked) {
                currentSelectedPeqDataItem = peqDataItemInfo;
                break;
            }
        }
        if (currentSelectedPeqDataItem == null) {
            currentSelectedPeqDataItem = peqDataItemInfos.get(0);
            currentSelectedPeqDataItem.ischecked = true;
        }
        return currentSelectedPeqDataItem;
    }

    private int getCurrentSelectedPeqDataItemPosition(List<PeqDataItemInfo> peqDataItemInfos) {
        if (peqDataItemInfos == null || peqDataItemInfos.isEmpty()) {
            return -1;
        }
        int currentSelectedItemPos = -1;
        for (PeqDataItemInfo peqDataItemInfo : peqDataItemInfos) {
            currentSelectedItemPos++;
            if (peqDataItemInfo.ischecked) {
                break;
            }
        }
        return currentSelectedItemPos;
    }

    public PeqData getCurrentSelectedPeqData(List<PeqDataItemInfo> peqDataItemInfos) {
        PeqData peqData;
        if (getCurrentSelectedPeqDataItemPosition(peqDataItemInfos) == 0) {
            peqData = PeqDataManager.getInstance().initNonePeqData();
        } else {
            String peqDataJson = readPeqData(getCurrentSelectedPeqDataItem(peqDataItemInfos).name);
            peqData = new Gson().fromJson(peqDataJson, PeqData.class);
        }
        return peqData;
    }

    public PeqData getPeqData(String name) {
        PeqData peqData = null;
        try {
            String peqDataJson = readPeqData(name);
            LogPlus.d("###peqDataJson:" + peqDataJson);
            peqData = new Gson().fromJson(peqDataJson, PeqData.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return peqData;
    }

    public List<PeqDataItemInfo> loadPeqDataListFromLocal() {
        List<PeqDataItemInfo> dataItemInfos = new ArrayList<>();

        String local = ShareprefenceTool.getInstance().getStringShareprefence(PEQ_DATA_ON_LOCAL_KEY, SmartPlayerApplication.getInstance(), "");
        if (BuildConfig.DEBUG) LogPlus.d("###localdatas:" + local);
        //[{"a":"无","b":false},{"a":"xb","b":false},{"a":"xxx","b":false},{"a":"风景线","b":true}]
        if (false && TextUtils.isEmpty(local)) {
            PeqDataItemInfo item = new PeqDataItemInfo();
            item.ischecked = true;
            item.name = SmartPlayerApplication.getInstance().getString(R.string.peq_mseb_none);
            dataItemInfos.add(item);
            return dataItemInfos;
        }
        try {
            Type listType = new TypeToken<List<PeqDataItemInfo>>() {
            }.getType();
            dataItemInfos = new Gson().fromJson(local, listType);
            if (false) {
                if (dataItemInfos != null && !dataItemInfos.isEmpty()) {
                    dataItemInfos.get(0).name = SmartPlayerApplication.getInstance().getString(R.string.peq_mseb_none);
                }
            }
            //LogPlus.d("###dataItemInfos:" + dataItemInfos);
            return dataItemInfos;
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            JSONArray jsonArray = new JSONArray(local);
            List<PeqDataItemInfo> peqDataItemInfos = new ArrayList<>(jsonArray.length());
            for (int i = 0, n = jsonArray.length(); i < n; ++i) {
                JSONObject jsonObject = (JSONObject) jsonArray.get(i);
                PeqDataItemInfo peqDataItemInfo = new PeqDataItemInfo();
                peqDataItemInfo.name = jsonObject.getString("a");
                peqDataItemInfo.ischecked = jsonObject.getBoolean("b");
                peqDataItemInfos.add(peqDataItemInfo);
            }
            //LogPlus.d("###dataItemInfos:" + dataItemInfos);
            return peqDataItemInfos;
        } catch (Exception e) {
            e.printStackTrace();
        }
        if(false){
            PeqDataItemInfo item = new PeqDataItemInfo();
            item.ischecked = true;
            item.name = SmartPlayerApplication.getInstance().getString(R.string.peq_mseb_none);
            dataItemInfos.add(item);
        }
        return dataItemInfos;
    }

    public PeqData initNonePeqData() {
        PeqData nonePeqData = null;
        String peqJsonData = readPeqData(TEMP_PEQ_DATA_KEY);
        if (!TextUtils.isEmpty(peqJsonData)) {
            nonePeqData = new Gson().fromJson(peqJsonData, PeqData.class);
        }
        if (nonePeqData == null) {
            nonePeqData = new PeqData();
            nonePeqData.name = SmartPlayerApplication.getInstance().getString(R.string.peq_mseb_none);
            nonePeqData.pre_amp = 0;
            nonePeqData.bands = new ArrayList<>();
            final int[] freqs = {31, 62, 125, 250, 500, 1000, 2000, 4000, 8000, 16000};
            final int bandsCount = freqs.length;
            for (int freq : freqs) {
                BandItem bandItem = new BandItem();
                bandItem.filter = 0;
                bandItem.freq = freq;
                bandItem.on = 0;
                bandItem.gain = 0;
                bandItem.q = 0.2;
                nonePeqData.bands.add(bandItem);
            }
        }
        return nonePeqData;
    }

    public void savePeqData(String show_name, String peqDataJson) {
        ShareprefenceTool.getInstance().setStringSharedPreference(show_name, peqDataJson, SmartPlayerApplication.getInstance());
    }

    public void savePeqDatasToLocal(List<PeqDataItemInfo> localDatas) {
        String localDatasJson = new Gson().toJson(localDatas);
        if (BuildConfig.DEBUG) {
            LogPlus.d("localdatas:" + localDatasJson);
        }
        ShareprefenceTool.getInstance().setStringSharedPreference(PEQ_DATA_ON_LOCAL_KEY, localDatasJson, SmartPlayerApplication.getInstance());
    }

    public String readPeqData(String showName) {
        String json = ShareprefenceTool.getInstance().getStringShareprefence(showName, SmartPlayerApplication.getInstance(), "");
        if (TextUtils.isEmpty(json)) return null;
        return json;
    }

    public void deletePeqDatas() {
        ShareprefenceTool.getInstance().delete(PEQ_DATA_ON_LOCAL_KEY, SmartPlayerApplication.getInstance());
    }

    public static class PeqInfo {
        private String url;
        private String name;
        private String show_name;
        private String describes;

        public String getShow_name() {
            return show_name;
        }

        public void setShow_name(String show_name) {
            this.show_name = show_name;
        }

        public String getUrl() {
            return url;
        }

        public void setUrl(String url) {
            this.url = url;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public String getDescribes() {
            return describes;
        }

        public void setDescribes(String describes) {
            this.describes = describes;
        }

        @Override
        public String toString() {
            return "PeqInfo{" +
                    "url='" + url + '\'' +
                    ", name='" + name + '\'' +
                    ", describes='" + describes + '\'' +
                    '}';
        }
    }

    public static class PeqDataItemInfo {
        //[{"a":"无","b":false},{"a":"xb","b":false},{"a":"xxx","b":false},{"a":"风景线","b":true}]
        @SerializedName("a")
        public String name;//name;
        @SerializedName("b")
        public boolean ischecked;//ischecked;
    }

    public static class PeqData implements java.io.Serializable {
        @SerializedName("a")
        public List<BandItem> bands;
        @SerializedName("b")
        public String name;
        @SerializedName("c")
        public double pre_amp;

        @Override
        public String toString() {
            return "PeqData{" +
                    "bands=" + bands +
                    ", name='" + name + '\'' +
                    ", pre_amp=" + pre_amp +
                    '}';
        }
    }

    public static class BandItem implements java.io.Serializable {
        @SerializedName("a")
        public double freq;
        @SerializedName("b")
        public double q;
        @SerializedName("c")
        public double gain;
        @SerializedName("d")
        public int on;
        @SerializedName("e")
        public int filter;

        @Override
        public String toString() {
            return "BandItem{" +
                    "freq=" + freq +
                    ", q=" + q +
                    ", gain=" + gain +
                    ", on=" + on +
                    ", filter=" + filter +
                    '}';
        }
    }

    private static final String TEMP_PEQ_DATA_KEY = "__temp__";
    private static final String PEQ_DATA_ON_LOCAL_KEY = "PEQ_DATA_ON_LOCAL_KEY";
}